<template>
  <div>
    <!--引用表格-->
    <BasicTable :showIndexColumn="true" ref="tableRef" @register="registerTable"
      :rowSelection="rowSelection" @fetch-success="onFetchSuccess" @row-click="rowClick">
      <!--插槽:搜索-->
      <template #form-workCenter="{ model, field }">
        <a-input-search v-model:value="model[field]" placeholder="请选择工作中心" readonly
          @search="workCenterOpen" />
      </template>
      <template #form-process="{ model, field }">
        <a-input-search v-model:value="model[field]" placeholder="请选择工艺" readonly
          @search="processOpen" />
      </template>
      <!-- <template #form-orderSelect="{ model, field }">
        <a-input-search v-model:value="model[field]" placeholder="请选择订单" readonly @search="orderListOpen" />
      </template> -->
      <!--插槽:表格顶部插槽-->
      <template #headerTop>
        <!-- 子表单区域 -->
        <a-tabs type="card" v-model:activeKey="activeKey" animated @change="handleChangeTabs">
          <a-tab-pane tab="主排产内容" key="mainSchedulingContent" :forceRender="true"></a-tab-pane>
          <a-tab-pane tab="下发汇总表" sty key="distributeSummaryTable">
            <a-table @change="tableChange" :pagination="ipagination"
              v-if="activeKey == 'distributeSummaryTable'" :dataSource="dataSourceTwo.data"
              :columns="columnsTwo" />
          </a-tab-pane>
          <a-tab-pane tab="排产甘特图" key="ganttChartProductionScheduling" :forceRender="true">
            <preGantt v-if="activeKey == 'ganttChartProductionScheduling'" :gttParams="gttParams"
              :dayColumns="dayColumns" />
          </a-tab-pane>
        </a-tabs>
      </template>
      <!--插槽:table标题-->
      <template #tableTitle>
        <a-button type="primary" preIcon="ant-design:export-outlined" @click="onExportXls"> 导出
        </a-button>
        <j-upload-button type="primary" preIcon="ant-design:import-outlined" @click="onImportXls">导入
        </j-upload-button>
        <a-button type="primary" @click="clickRelease">释放</a-button>
        <a-button type="primary" @click="clickDistributePlan">
          下发</a-button>
        <a-button type="primary" @click="clickUnDistributePlan">
          撤发</a-button>
        <!-- <super-query :config="superQueryConfig" @search="handleSuperQuery" /> -->
        <a-dropdown v-if="selectedRowKeys.length > 0">
          <template #overlay>
            <a-menu>
              <a-menu-item key="1" @click="batchHandleDelete">
                <Icon icon="ant-design:delete-outlined"></Icon>
                删除
              </a-menu-item>
            </a-menu>
          </template>
          <a-button>批量操作
            <Icon icon="mdi:chevron-down"></Icon>
          </a-button>
        </a-dropdown>
        <a-select v-model:value="formState.lineDateStatus" style="width: 120px"
          :options="lineDateStatusOptions" @change="handleChangeSelect" />
        <a-select v-model:value="formState.whetherIssue" style="width: 120px"
          :options="whetherIssueOptions" @change="handleChangeSelect" />
        <a-select v-model:value="formState.isReleased" style="width: 120px"
          :options="isReleasedOptions" @change="handleChangeSelect" />
      </template>
      <!--操作栏-->
      <template #action="{ record }">
        <TableAction :actions="getTableAction(record)"
          :dropDownActions="getDropDownAction(record)" />
      </template>
      <!--字段回显插槽-->
      <template #htmlSlot="{ text }">
        <div v-html="text"></div>
      </template>
      <!--省市区字段回显插槽-->
      <template #pcaSlot="{ text }">
        {{ getAreaTextByCode(text) }}
      </template>
      <template #fileSlot="{ text }">
        <span v-if="!text" style="font-size: 12px; font-style: italic">无文件</span>
        <a-button v-else :ghost="true" type="primary" preIcon="ant-design:download-outlined"
          size="small" @click="downloadFile(text)">下载</a-button>
      </template>
    </BasicTable>
    <!-- 表单区域 -->
    <PsProductionArrangementPlansModal @register="registerModal" @success="handleSuccess" />
    <div class="jeecg-basic-table jeecg-basic-table-form-container"
      v-if="activeKey == 'mainSchedulingContent'">
      <!-- 排产子表详情数据 -->
      <div>日排产明细</div>
      <a-table :columns="sonTableColumns" :loading="sonTableLoading"
        :data-source="sonTable.sonTableData" bordered size="small">
        <template #bodyCell="{ column, text, record }">
          <template
            v-if="['schedulingTime','startTime', 'endTime', 'quantity'].includes(column.dataIndex)">
            <div v-if="editableData[record.id]">
              <template v-if="['schedulingTime' ].includes(column.dataIndex)">
                <a-date-picker v-model:value="editableData[record.id][column.dataIndex]"
                  valueFormat="YYYY-MM-DD" />
              </template>
              <template v-else-if="['startTime', 'endTime'].includes(column.dataIndex)">
                <a-date-picker v-model:value="editableData[record.id][column.dataIndex]"
                  format="YYYY-MM-DD HH:mm:ss" valueFormat="YYYY-MM-DD HH:mm:ss" />
              </template>
              <template v-else-if="['quantity'].includes(column.dataIndex)">
                <a-input-number v-model:value="editableData[record.id][column.dataIndex]" />
              </template>
            </div>
            <template v-else>
              {{ text }}
            </template>
          </template>
          <template v-else-if="column.dataIndex === 'operation'">
            <div class="editable-row-operations">
              <a-popconfirm title="确定删除此条数据吗?" @confirm="candel(record)"
                v-if="hasPermission('ps:ps_production_arrangement_plans_day_detalis:delete')">
                <a style="color:red">删除</a>
              </a-popconfirm>
              <a-divider type="vertical" />
              <span v-if="editableData[record.id]">
                <a @click="save(record.id)">保存</a>
                <a-divider type="vertical" />
                <a-popconfirm title="确定取消编辑吗?" @confirm="cancel(record.id)">
                  <a>取消</a>
                </a-popconfirm>
              </span>
              <span v-else>
                <a @click="edit(record.id)">编辑</a>
              </span>
            </div>
          </template>
        </template>
      </a-table>
    </div>
  </div>
  <!-- 工作中心 -->
  <workCenterSelectModel @register="workCenterSelectModal"
    @getSelectResult="workCenterHandleSuccess"></workCenterSelectModel>
  <!-- 订单选择 -->
  <orderSelectModel @register="orderRegModal" @getSelectResult="orderhandleSuccess" />
  <!-- 单据类型 -->
  <billTypeSelectModel @register="billTypeRegModal" @getSelectResult="billTypehandleSuccess" />
  <!-- 工艺选择 -->
  <ProcessModal @register="processRegister" @getSelectResult="handleProcesshanged" />
</template>

<script lang="ts" name="psProductionArrangementPlans-psProductionArrangementPlans" setup>
  import {
    ref,
    computed,
    unref,
    toRaw,
    reactive
  } from 'vue';
  import {
    BasicTable,
    useTable,
    TableAction
  } from '/@/components/Table';
  import {
    useListPage
  } from '/@/hooks/system/useListPage';
  import {
    useModal
  } from '/@/components/Modal';
  import billTypeSelectModel from '/@/views/components/billTypeSelectModel.vue';
  import PsProductionArrangementPlansModal from './components/PsProductionArrangementPlansModal.vue';
  import ProcessModal from '/@/views/components/processManagementSelectModels.vue';
  import {
    columns,
    searchFormSchema
  } from './PsProductionArrangementPlans.data';
  import {
    getList,
    gttUrl,
    deleteOne,
    batchDelete,
    getImportUrl,
    getExportUrl,
    releaseOrder,
    distributePlan,
    unDistributePlan,
    psProductionArrangementPlansDistribute,
    getDetailItem,
    deleteDetailItem,
    postChangeProductionArrangementPlansDayDetalis
  } from './PsProductionArrangementPlans.api';

  import {
    downloadFile
  } from '/@/utils/common/renderUtils';
  import {
    useMessage
  } from '/@/hooks/web/useMessage';
  import {
    useI18n
  } from '/@/hooks/web/useI18n';
  import {
    defHttp
  } from '/@/utils/http/axios';
  import preGantt from '/@/views/components/preGantt.vue';
  import workCenterSelectModel from '/@/views/components/workCenterSelectModel.vue';
  import orderSelectModel from '/@/views/components/orderSelectModel.vue';
  import {
    setAdvancedQuery
  } from '/@/utils/util';
  import {
    usePermission
  } from '/@/hooks/web/usePermission';
  const {
    hasPermission
  } = usePermission();
  const checkedKeys = ref < Array < string | number >> ([]);
  const tableRef = ref < Nullable < TableActionType >> (null);
  const activeKey = ref('mainSchedulingContent');
  const gttParams = reactive({});
  const {
    createMessage
  } = useMessage();
  const {
    t
  } = useI18n();
  const activeParentId = ref(null);
  const sonTableLoading = ref < boolean > (false);
  // 高级查询配置
  // const superQueryConfig = setAdvancedQuery(columns);
  let dayColumns = reactive([]);
  const formState = reactive({
    lineDateStatus: '0',
    whetherIssue: null,
    isReleased: null,
  });

  //执行查询
  function handleSuperQuery(params) {
    setProps({
      searchInfo: toRaw(params)
    });
    reload();
  }
  const ipaginations = {
    current: 1,
    pageSize: 10,
    pageSizeOptions: ['10', '20', '30'],
    showTotal: (total, range) => {
      return range[0] + '-' + range[1] + ' 共' + total + '条';
    },
    showQuickJumper: true,
    showSizeChanger: true,
    total: 0,
  };

  function tableChange(pagination) {
    ipagination.value.current = pagination.current;
    ipagination.value.pageSize = pagination.pageSize;
    getPsProductionArrangementPlansDistributeList();
  }
  const ipagination = ref(ipaginations);
  //注册model
  const [registerModal, {
    openModal
  }] = useModal();
  const [workCenterSelectModal, {
    openModal: openWorkCenterModal
  }] = useModal();
  const [orderRegModal, {
    openModal: openOrderListModal
  }] = useModal();
  const [billTypeRegModal, {
    openModal: openBillTypeModal
  }] = useModal();
  const [processRegister, {
    openModal: openProcessModal
  }] = useModal();
  //注册table数据
  const {
    prefixCls,
    tableContext,
    onExportXls,
    onImportXls
  } = useListPage({
    tableProps: {
      title: '排产计划',
      columns,
      api: getList,
      canResize: false,
      showTable: true,
      formConfig: {
        labelWidth: 120,
        schemas: searchFormSchema,
        autoSubmitOnEnter: true,
        showAdvancedButton: true,
        fieldMapToNumber: [],
        fieldMapToTime: [],
      },
      showActionColumn: false, //是否显示操作列
      actionColumn: {
        width: 120,
        fixed: 'right',
      },
      // 请求之前对参数做处理
      beforeFetch(params) {
        // 下面这三个参数必填
        // if(activeKey.value == "mainSchedulingContent") {
        params.lineDateStatus = formState.lineDateStatus;
        params.whetherIssue = formState.whetherIssue;
        params.isReleased = formState.isReleased;
        // }

        // 如果当前tab是甘特图  就处理甘特图的请求参数
        if (activeKey.value == 'ganttChartProductionScheduling') {
          gttParams.value = {
            schedulingTime: params.operateTime,
            workCenter: params.workCenter,
            lineDate: params.lineDate,
            orderNumber: params.orderNumber,
            createBy: params.createBy,
            // isReleased: params.isReleased,
            lineDateStatus: formState.lineDateStatus,
            whetherIssue: formState.whetherIssue,
            isReleased: formState.isReleased,
          };
        }
      },
      // 请求后对返回值进行处理
      afterFetch(res) {
        let weekColumns = res[0].weeks.map((item) => {
          return {
            title: `${item.week}计划`,
            align: 'right',
            width: 120,
            dataIndex: `week${item.week}`,
          };
        });
        dayColumns = res[0].days.map((item, idx) => {
          return {
            title: item.day,
            align: 'right',
            width: 120,
            dataIndex: `day${idx}`,
          };
        });
        let tempColumns = [...columns, ...weekColumns, ...dayColumns];
        setColumns(tempColumns);
      },
    },
    exportConfig: {
      name: '排产计划',
      url: getExportUrl,
    },
    importConfig: {
      url: getImportUrl,
      success: handleSuccess,
    },
  });
  // 当前  select
  const lineDateStatusOptions = ref < SelectProps['options'] > ([{
      value: '0',
      label: '当前日',
    },
    {
      value: '1',
      label: '当前月',
    },
    {
      value: '2',
      label: '双月上',
    },
    {
      value: '3',
      label: '双月下',
    },
    {
      value: '4',
      label: '全部',
    },
  ]);
  // 下发  select
  const whetherIssueOptions = ref < SelectProps['options'] > ([{
      value: null,
      label: '全部',
    },
    {
      value: '0',
      label: '未下发',
    },
    {
      value: '1',
      label: '已下发',
    },
  ]);
  // 释放  select
  const isReleasedOptions = ref < SelectProps['options'] > ([{
      value: null,
      label: '全部',
    },
    {
      value: '0',
      label: '未释放',
    },
    {
      value: '1',
      label: '已释放',
    },
  ]);
  // 排产计划子表详情数据
  const sonTable = reactive({
    sonTableData: []
  });

  function handleChangeSelect() {
    setProps({
      lineDateStatus: formState.lineDateStatus,
      whetherIssue: formState.whetherIssue,
      isReleased: formState.isReleased,
    });
    reload();
  }

  const titleBox = document.getElementsByClassName('jeecg-basic-table-header__table-title-box');
  const tableContainer = document.getElementsByClassName('ant-table-container');
  // const pagination = document.getElementsByClassName('ant-pagination');
  const alertInfo = document.getElementsByClassName('ant-alert-info');

  function handleChangeTabs(e) {
    let showTable = false;
    activeKey.value = e;
    titleBox[0].style.display = e == 'mainSchedulingContent' ? 'flex' : 'none';
    tableContainer[0].style.display = e == 'mainSchedulingContent' ? 'flex' : 'none';
    tableContainer.length > 1 ? (tableContainer[1].style.display = e == 'mainSchedulingContent' ?
      'flex' : 'none') : '';
    // pagination[0].style.display = e == 'mainSchedulingContent' ? 'flex' : 'none';
    alertInfo[0].style.display = e == 'mainSchedulingContent' ? 'flex' : 'none';
    showTable = e == 'mainSchedulingContent';
    // if (e == 'mainSchedulingContent') {
    //   showTable = true;

    // }
    if (e == 'distributeSummaryTable') {
      getPsProductionArrangementPlansDistributeList();
      // psProductionArrangementPlansDistribute({ pageNo: 1, pageSize: 10 }).then(res => {
      //   console.log(res);

      // })
    }
    if (e == 'ganttChartProductionScheduling') {
      // 通过getForm获取表单的方法，再通过getFieldsValue获取表单的数据
      let data = getForm().getFieldsValue();
      // tab是甘特图时   将参数带给甘特图
      gttParams.value = {
        schedulingTime: data?.operateTime,
        workCenter: data?.workCenter,
        lineDate: data?.lineDate,
        orderNumber: data?.orderNumber,
        createBy: data?.createBy,
        // isReleased: data?.isReleased, 
        lineDateStatus: formState.lineDateStatus,
        whetherIssue: formState.whetherIssue,
        isReleased: formState.isReleased,
      };
    }
    setProps({
      showTable: showTable
    });
  }
  const getPsProductionArrangementPlansDistributeList = () => {
    defHttp
      .get({
        url: '/ps/psProductionArrangementPlansDistribute/list',
        params: {
          pageNo: ipagination.value.current,
          pageSize: ipagination.value.pageSize,
          finalAssembly: 0
        },
      })
      .then((res) => {
        dataSourceTwo.data = res.records;
        
      });
  };

  function processOpen() {
    openProcessModal(true, {
      isUpdate: false,
      showFooter: true,
    });
  }

  // 行内编辑数据及方法
  const dataSource = ref([]);
  const editableData: UnwrapRef < Record < string, DataItem >> = reactive({});

  const edit = (id: string) => {
    editableData[id] = cloneDeep(dataSource.value.filter(item => id === item.id)[0]);
  };
  const save = (id: string) => {
    Object.assign(dataSource.value.filter(item => id === item.id)[0], editableData[id]);
    postChangeProductionArrangementPlansDayDetalis(editableData[id]);
    rowClick(editableData[id].parentId);
    delete editableData[id];
  };
  const cancel = (id: string) => {
    delete editableData[id];
  };
  const candel = async (record: object) => {
    let params = {
      id: record.id
    };
    await deleteDetailItem(params);
    rowClick(record.parentId);
  };
  // 排产计划  子表详情columns
  const sonTableColumns = reactive(
    [{
        title: "序号",
        customRender: (text, record, index) => text.index + 1
      },
      {
        title: '资源名称',
        dataIndex: 'resourceName',
      },
      {
        title: '产品编码',
        dataIndex: 'productCode',
      },
      {
        title: '产品名称',
        dataIndex: 'productName',
      },
      {
        title: '上线日期',
        dataIndex: 'schedulingTime',
      },
      {
        title: '开始时间',
        dataIndex: 'startTime',
      },
      {
        title: '结束时间',
        dataIndex: 'endTime',
      },
      {
        title: '数量',
        dataIndex: 'quantity',
      },
      {
        title: '耗时',
        dataIndex: '',
      },
      {
        title: '备注',
        dataIndex: 'remark',
      },
      {
        title: '操作',
        dataIndex: 'operation',
        align: 'center',
        fixed: 'right'
      },
    ]
  );
  // 设置选中行的样式
  function setActiveLineStyle(record) {
    if (record.id == activeParentId.value) {
      return 'activeLine'
    }
  };
  // 根据点击的列的id  请求排产计划当天详情的子表数据
  async function rowClick(record, index, e) {
    sonTableLoading.value = true;
    // 通过组件回调的rowClick record是个对象，index是点击的表格的索引  所以可以通过index判断rowClick是点击列表触发还是我们自己调用的  以此达到取不同值的问题
    let id = null;
    // 代表通过组件回调的rowClick
    if (index !== undefined) {
      id = record.id;
      activeParentId.value = record.id;
    } else {
      // 代表自己触发的rowClick
      id = record;
    }
    let params = {
      parentId: id
    };
    let res = await getDetailItem(params);
    setTimeout(() => {
      sonTable.sonTableData = res.records;
      dataSource.value = res.records;
      sonTableLoading.value = false;
    }, 200);
  }
  // 打开工作中心模块
  function workCenterOpen() {
    openWorkCenterModal(true, {
      isUpdate: false,
      showFooter: true,
    });
  }
  // 工作中心选择
  function workCenterHandleSuccess(val, values) {
    getForm().setFieldsValue({
      workCenterId: val[0].item.id,
      workCenter: val[0].item.workCenterName,
    });
  }

  function orderListOpen() {
    openOrderListModal(true, {
      isUpdate: false,
      showFooter: true,
    });
  }
  // 订单选择
  function orderhandleSuccess(val, values) {
    getForm().setFieldsValue({
      orderNumber: val[0].item.billCode,
    });
  }
  const [registerTable, {
    reload,
    setProps,
    getForm,
    setColumns,
    getDataSource,
    setTableData
  }, {
    rowSelection,
    selectedRowKeys
  }] = tableContext;
  // 下发计划
  const clickDistributePlan = async () => {
    if (selectedRowKeys.value.length > 0) {
      let ids = selectedRowKeys.value.toString();
      await distributePlan({
        itemIds: ids
      }).catch((err) => {
        console.log('errrrrrrrrrrrrrr', err);
      });
      handleSuccess();
    } else createMessage.warning(t('请先选择数据'));
  };
  // 取消下发计划
  const clickUnDistributePlan = async () => {
    if (selectedRowKeys.value.length > 0) {
      let ids = selectedRowKeys.value.toString();
      await unDistributePlan({
        itemIds: ids
      }).catch((err) => {
        console.log('errrrrrrrrrrrrrr', err);
      });
      handleSuccess();
    } else createMessage.warning(t('请先选择数据'));
  };
  /**
   * 释放事件
   */
  const clickRelease = async () => {
    if (selectedRowKeys.value.length > 0) {
      openBillTypeModal(true, {
        isUpdate: false,
        showFooter: true,
        tableName: 'bus_product_order',
      });
    } else createMessage.warning(t('请先选择数据'));
  };
  //单据类型回写
  async function billTypehandleSuccess(val, values) {
    let params = {
      itemIds: selectedRowKeys.value.toString(),
      billTypeId: val[0].value,
    };
    await releaseOrder(params);
    handleSuccess();
  }
  // 工艺选择回写
  function handleProcesshanged(val) {
    getForm().setFieldsValue({
      processId: val[0].item.id,
      process: val[0].item.processName,
    });
  }
  /**
   * 接口请求成功后回调
   */
  function onFetchSuccess(result) {
    let tableData = getDataSource();
    // 获取数据后 处理数据赋值进表格
    tableData.map((item) => {
      let weeksData = item.weeks;
      let dayData = item.days;
      weeksData.forEach((val, idx) => {
        item['week' + val.week] = val.dayQuantity;
      });
      dayData.forEach((val, idx) => {
        item['day' + idx] = val.dayQuantity;
      });
    });
  }

  /**
   * 编辑事件
   */
  function handleEdit(record: Recordable) {
    openModal(true, {
      record,
      isUpdate: true,
      showFooter: true,
    });
  }
  /**
   * 详情
   */
  function handleDetail(record: Recordable) {
    openModal(true, {
      record,
      isDetail: true,
      isUpdate: true,
      showFooter: false,
    });
  }
  /**
   * 删除事件
   */
  async function handleDelete(record) {
    await deleteOne({
        id: record.id,
      },
      handleSuccess
    );
  }
  /**
   * 批量删除事件
   */
  async function batchHandleDelete() {
    await batchDelete({
        ids: selectedRowKeys.value,
      },
      handleSuccess
    );
  }
  /**
   * 成功回调
   */
  function handleSuccess() {
    (selectedRowKeys.value = []) && reload();
  }
  /**
   * 操作栏
   */
  function getTableAction(record) {
    return [{
      label: '编辑',
      onClick: handleEdit.bind(null, record),
    }, ];
  }

  /**
   * 下拉操作栏
   */
  function getDropDownAction(record) {
    return [{
        label: '详情',
        onClick: handleDetail.bind(null, record),
      },
      {
        label: '删除',
        popConfirm: {
          title: '是否确认删除',
          placement: 'left',
          confirm: handleDelete.bind(null, record),
        },
      },
    ];
  }
  const dataSourceTwo = reactive({
    data: []
  });

  const columnsTwo = [{
      title: '排产日期',
      dataIndex: 'createTime',
      key: 'createTime',
    },
    {
      title: '订单编号',
      dataIndex: 'orderNumber',
      key: 'orderNumber',
    },
    {
      title: '行号',
      dataIndex: 'rowNum',
      key: 'rowNum',
    },
    {
      title: '产品编码',
      dataIndex: 'materialCode',
      key: 'materialCode',
    },
    {
      title: '产品名称',
      dataIndex: 'materialName',
      key: 'materialName',
    },
    {
      title: '排产数量',
      dataIndex: 'totalQuantity',
      key: 'totalQuantity',
    },
    {
      title: '上线日期',
      dataIndex: 'lineDate',
      key: 'lineDate',
    },
  ];

</script>

<style lang="less" scoped>
  .activeLine {
    background-color: rgba(255, 192, 203, .4)
  }

</style>
